package util

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"strconv"
	"time"
)

var jwtSecret []byte

type ClaimsNew struct {
	Jti     int64 `json:"jti"`
	ExpTime int64 `json:"exp_time"`
	// Claims
	jwt.StandardClaims
}

// GenerateToken generate tokens used for auth
func GenerateToken(id int64) (string, error) {
	nowTime := time.Now()
	expireTime := nowTime.Add(3 * time.Hour).Unix()
	//通过名字查询当前用户的uid
	claims := ClaimsNew{
		id,
		expireTime,
		jwt.StandardClaims{
			ExpiresAt: expireTime,
			Issuer:    strconv.FormatInt(id, 10),
			Id:        strconv.FormatInt(id, 10),
		},
	}
	fmt.Println(strconv.FormatInt(id, 10))
	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	token, err := tokenClaims.SignedString([]byte(jwtSecret))
	return token, err
}

// ParseToken parsing token
func ParseToken(token string) (*ClaimsNew, error) {
	tokenClaims, err := jwt.ParseWithClaims(token, &ClaimsNew{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(jwtSecret), nil
	})
	if tokenClaims != nil {
		if claims, ok := tokenClaims.Claims.(*ClaimsNew); ok && tokenClaims.Valid {
			return claims, nil
		}
	}

	return nil, err
}

// ParseToken parsing token
func ParsePhpToken(token string) (*ClaimsNew, error) {
	tokenClaims, err := jwt.ParseWithClaims(token, &ClaimsNew{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(jwtSecret), nil
	})

	if tokenClaims != nil {
		if claims, ok := tokenClaims.Claims.(*ClaimsNew); ok && tokenClaims.Valid {
			return claims, nil
		}
	}

	return nil, err
}
